package org.example.votingsystem.web;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.votingsystem.account.Result;
import org.example.votingsystem.dao.AccountYearPeopleDao;
import org.example.votingsystem.util.JWTUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/api/yearPeopleDo")
public class yearPeopleDoServelet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//
        AccountYearPeopleDao accountYearPeopleDao = new AccountYearPeopleDao();

        String token = req.getHeader("token");
        DecodedJWT decodedJWT = JWTUtil.getTokenInfo(token);
        String id = decodedJWT.getClaim("id").asString();
        try {
//            check user has voted ?
            if(accountYearPeopleDao.checkVoteRecord(id)){
                Result result = new Result(200,"你已经投票了",null);
                resp.getWriter().write(new ObjectMapper().writeValueAsString(result));
            }
        } catch (SQLException e) {
            Result result = new Result(500,"error",null);
            resp.getWriter().write(new ObjectMapper().writeValueAsString(result));
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String account = req.getParameter("account");
        System.out.println(account);

//        操作人
        String token = req.getHeader("token");
        DecodedJWT decodedJWT = JWTUtil.getTokenInfo(token);
        String id = decodedJWT.getClaim("id").asString();
        System.out.println(id);
//        给投票数+1
        AccountYearPeopleDao accountYearPeopleDao = new AccountYearPeopleDao();
        try {
            accountYearPeopleDao.addCounts(Integer.parseInt(account),id);
            Result result = new Result(200,"投票成功",null);
            resp.getWriter().write(new ObjectMapper().writeValueAsString(result));
        } catch (SQLException e) {
            Result result = new Result(500, "error", null);
            resp.getWriter().write(new ObjectMapper().writeValueAsString(result));
        }

    }
}
